// pages/index/index.js
import {
  API,
  getUrl
} from '../../utils/api'
import {
  checkPhone
} from '../../utils/util'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl'),
    phoneNumber: '',
    openid: '',
    sessionKey: '',
    address: '', // 详细地址
    addressCode: [], // 省市区code
    addressName: [], // 省市区code
    addressSumName: '',
    classes: '', // 班级
    familyName: '', // 家长姓名
    userPhoto: '../../images/head.png', // 头像   
    tabbarIndex: 0, // 默认显示  tab1
    isFirstUse: false, // 引导添加到桌面
    grade: '', // 年级
    nickName: '', // 昵称
    register: false, // 完善个人信息,
    schoolId: '', // 学校ID
    schoolName: '', // 学校名称
    studentName: '', // 学生姓名
    videoId: '', // 上次看到视频ID
    videoName: '', // 上次看到视频名称
    tabList: [{
        "text": "首页",
        "iconPath": "/images/home.png",
        "selectedIconPath": "/images/home-select.png",
      },
      {
        "text": "我的",
        "iconPath": "/images/user.png",
        "selectedIconPath": "/images/user-select.png",
      }
    ],
    videoList: [],
    showVideoList: [],
    scrollTop: 0, // 滚动到上一次位置  
    schoolList: [], // 全部学校列表
    schoolIndex: -1,
    clasaList: [],
    gradeAndClassIndex: [],
    userPhone: '',
    errorMsg: '',
    imageHeight:'180px'
  },
  searchNameInput(e) {
    if (e.detail.value) {
      this.setData({
        showVideoList: this.data.videoList.filter(vedio => vedio.name.indexOf(e.detail.value) > -1)
      })
    } else {
      this.setData({
        showVideoList: this.data.videoList
      })
    }
  },
  tabChange(e) {
    let index = e.detail.index;
    this.setData({
      tabbarIndex: index
    })
    if (index == 0) {
      wx.setNavigationBarTitle({
        title: '首页'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '个人中心'
      })
    }
  },
  closeTopMessage() {
    this.setData({
      lastVideoMessage: ''
    })
  },
  closeMask() {
    this.setData({
      isFirstUse: false
    })
  },
  closeMsgDialog() {
    this.setData({
      errorMsg: ''
    })
  },
  choseUserPhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: (res) => {
        //1、取出路径
        const path = res.tempFilePaths[0]

        //2、设置imagePath
        this.setData({
          userPhoto: path
        })
      }
    })
  },
  bindAddressPickerChange(e) {
    this.setData({
      addressCode: e.detail.code,
      addressName: e.detail.value
    })
    this.setData({
      addressSumName: this.getAddressSumName()
    });
  },
  bindSchoolPickerChange(e) {
    this.setData({
      schoolIndex: e.detail.value,
      gradeAndClassIndex: []
    })
  },
  bindGradeAndClassPickerChange(e) {
    this.setData({
      gradeAndClassIndex: e.detail.value
    })
  },
  getAddressSumName() {
    if (this.data.addressName.length == 0) {
      return '';
    }
    let address = '';
    for (let index = 0; index < this.data.addressName.length; index++) {
      address += this.data.addressName[index];
    }
    return address;
  },
  handleAddressInfo(userInfo) {
    // 省市区编码
    if (userInfo.provinceCode) {
      let addressCode = [userInfo.provinceCode];
      let addressName = [userInfo.province];
      if (userInfo.cityCode) {
        addressCode.push(userInfo.cityCode);
        addressName.push(userInfo.city)
        if (userInfo.countyCode) {
          addressCode.push(userInfo.countyCode);
          addressName.push(userInfo.county);
        }
      }
      this.setData({
        addressCode: addressCode,
        addressName: addressName
      })

      this.setData({
        addressSumName: this.getAddressSumName()
      });

    }
  },
  getAllSchoolList() {
    wx.request({
      url: getUrl(API.SCHOOL_LIST),
      success: (res) => {
        this.handelSchoolInfo(res.data.data);
        this.goToUserPage();
      }
    });
  },
  handelSchoolInfo(data) {
    this.setData({
      schoolList: data
    })
    if (this.data.schoolId) {
      let index = data.findIndex(school => school.schoolId == this.data.schoolId);
      this.setData({
        schoolIndex: index
      })
      if (this.data.grade) {
        let gradeIndex = data[index].gradeList.findIndex(grade => grade == this.data.grade);
        let classesIndex = this.data.clasaList.findIndex(c => c == this.data.classes);
        let gradeAndClassIndex = [gradeIndex, classesIndex];
        this.setData({
          gradeAndClassIndex: gradeAndClassIndex
        })
      }
    }

  },
  bindInput(e) {
    let data = {};
    data[e.target.dataset.key] = e.detail.value;
    this.setData(data)
  },
  openVideo(e) {
    let mediaId = e.currentTarget.dataset.mediaid;
    if (mediaId)
      wx.request({
        url: getUrl(API.GET_VIDEO),
        data: {
          openid: this.data.openid,
          mediaId: mediaId
        },
        success: (res) => {
          this.setData({
            videoName:e.currentTarget.dataset.name
          })
          wx.navigateTo({
            url: '../video-page/index',
            success: (pageRes) => {
              pageRes.eventChannel.emit('sendData', res.data.data)
            }
          })

        }
      });
  },
  getVedioList() {
    wx.request({
      url: getUrl(API.VIDEO_LIST),
      data: {
        openid: this.data.openid
      },
      success: (res) => {
        if (res.data.data) {
          this.setData({
            videoList: res.data.data,
            showVideoList: res.data.data
          });
          let index = res.data.data.findIndex(video => video.name == this.data.videoName);
          this.setData({
            scrollTop: index * (246 + 20)
          })
          if(this.data.videoList.length>0){
            var obj = wx.createSelectorQuery();
            let image = obj.select('.image-box')
            image.boundingClientRect( (rect)=> {            
              this.setData({
                imageHeight:rect.width/16*9+'px'
              })
            }).exec()
          }
          
        }
      }
    });
  },
  goToUserPage() {
    if (!this.data.register) {
      wx.navigateTo({
        url: '../userInfo/index',
        success: (res) => {
          res.eventChannel.emit('sendData', this.data)
        },
        events: {
          saveData: (data) => {
            if (data)
              this.setUserInfo(data);
          }
        }
      })
      return false;
    }
  },
  bindSumbitBtnClick(e) {
    this.onSubmit();
  },
  onSubmit() {
    let params = {};
    let msg = '';
    if (this.data.addressCode.length != 3) {
      msg = "请选择所在地区"
    } else {
      params.provinceCode = this.data.addressCode[0];
      params.province = this.data.addressName[0];
      params.cityCode = this.data.addressCode[1];
      params.city = this.data.addressName[1];
      params.countyCode = this.data.addressCode[2];
      params.county = this.data.addressName[2];
    }

    if (this.data.schoolIndex == -1) {
      msg = "请选择所在学校"
    } else {
      params.schoolId = this.data.schoolList[this.data.schoolIndex].schoolId;
      params.schoolName = this.data.schoolList[this.data.schoolIndex].schoolName;
    }

    if (this.data.gradeAndClassIndex.length != 2) {
      msg = "请选择所在班级"
    } else {
      let gradeList = this.data.schoolList[this.data.schoolIndex].gradeList;
      params.grade = gradeList[this.data.gradeAndClassIndex[0]];
      params.classes = this.data.clasaList[this.data.gradeAndClassIndex[1]];
    }

    if (this.data.studentName) {
      params.studentName = this.data.studentName;
    } else {
      msg = "请输入学生姓名";
    }

    if (this.data.familyName) {
      params.familyName = this.data.familyName;
    } else {
      msg = "请输入家长姓名";
    }

    if (this.data.phoneNumber) {
      if (!checkPhone(this.data.phoneNumber)) {
        msg = "手机号格式不正确";
      } else {
        params.phoneNumber = this.data.phoneNumber;
      }
    } else {
      msg = "请输入家长手机号";
    }

    if (this.data.address) {
      params.address = this.data.address;
    } else {
      msg = "请输入家庭地址";
    }

    if (msg) {
      this.setData({
        errorMsg: msg
      })
      return;
    }
    params.openid = this.data.openid;
    wx.request({
      url: getUrl(API.USER_SAVE),
      method: "POST",
      data: params,
      success: (res) => {
        this.setUserInfo(res.data.data);
        if (res.data.data) {
          this.setData({
            errorMsg:res.data.msg
          })
        } else {
          this.setData({
            errorMsg: res.data.msg||'保存失败'
          })
        }
      }
    });
  },
  setUserInfo(userInfo) {
    if (userInfo) {
      this.setData({
        phoneNumber: userInfo.phoneNumber || '',
        sessionKey: userInfo.session_key,
        isFirstUse: userInfo.firstLogin,
        userPhoto: userInfo.avatarUrl || this.data.userPhoto,
        address: userInfo.address,
        classes: userInfo.classes,
        grade: userInfo.grade,
        familyName: userInfo.familyName,
        nickName: userInfo.nickName,
        register: userInfo.register,
        schoolId: userInfo.schoolId,
        schoolName: userInfo.schoolName,
        studentName: userInfo.studentName,
        videoId: userInfo.videoId,
        videoName: userInfo.videoName
      })
      this.handleAddressInfo(userInfo);
      this.getAllSchoolList();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    let clasaList = [];
    for (let i = 1; i <= 35; i++) {
      clasaList.push(i + '班');
    }
    this.setData({
      clasaList: clasaList
    })

    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: getUrl(API.OAUTH),
            data: {
              code: res.code
            },
            success: (res) => {

              this.setData({
                openid: res.data.data.openid
              })
              this.setUserInfo(res.data.data)
              this.getVedioList();
            }
          })
        }
      }
    })
  }
})